/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.freemarker.directive;

import vip.dexian.admin.service.AdminService;
import vip.dexian.common.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 控制对应的权限是否展示
 *
 * @author 挺好的 2023年05月30日 15:55
 */
@Component ("permissionDirective")
public class PermissionDirective extends BaseDirective {

    /**
     * 权限的参数名称
     */
    private static final String PERMS_NAME_PARAMETER_NAME = "name";

    /**
     * 管理员
     */
    @Resource (name = "adminServiceImpl")
    private AdminService adminService;

    /**
     * 控制权限的隐藏和显示
     *
     * @param env
     * @param params
     * @param loopVars
     * @param body
     *
     * @throws freemarker.template.TemplateException
     * @throws java.io.IOException
     */
    @Override
    public void execute (Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {

        String name = FreeMarkerUtils.getParameter(PERMS_NAME_PARAMETER_NAME, String.class, params);

        if (body == null) {
            return;
        }

        boolean hasPermission = this.adminService.hasPermission(name);
        // 有权限，才展示该菜单
        if (hasPermission) {
            body.render(env.getOut());
        }
    }
}
